package generic.no2;

import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Scanner;

public class ArraySwapper {
	public static <T extends Comparable<T>>
	boolean swap(T[] ts,T t1,T t2){
		LinkedList<T> linkedList=new LinkedList<>();
		int loc=0;
		for (int index=0;index<ts.length;index++){
			if(ts[index].compareTo(t1)==0)
				switch(linkedList.size()){
					case 0:
						loc=index;
						linkedList.add(t1);
						break;
					case 1:
						if(linkedList.getFirst()==t1){
							System.out.println("第一个元素出现多次");
							return false;
						}
						else{
							ts[loc]=t1;
							ts[index]=t2;
							linkedList.add(t2);
							for(T t:ts) System.out.println(t);
							return true;
						}
				}
			else if(ts[index].compareTo(t2)==0)
				switch(linkedList.size()){
					case 0:
						loc=index;
						linkedList.add(t2);
						break;
					case 1:
						if(linkedList.getFirst()==t2){
							System.out.println("第二个元素出现多次");
							return false;
						}
						else{
							ts[loc]=t2;
							ts[index]=t1;
							linkedList.add(t1);
							for(T t:ts) System.out.println(t);
							return true;
						}
				}
		}
		switch (linkedList.size()) {
			case 0:	System.out.println("两个元素均未找到");
			case 1:	System.out.println("一个元素未找到");
			default:System.out.println("未知错误");
		}
		return false;
	}
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		LinkedList<Integer> linkedList = new LinkedList<>();
		System.out.println("请输入数组元素：(输入其他字符退出输入)");
		while (true) {
			try {
				linkedList.add(scanner.nextInt());
			} catch (InputMismatchException inputMismatchException) {
				scanner.next();
				break;
			}
		}
		System.out.println("请输入待交换的元素（2个）");
		while (true){
			try {
				if (!swap(linkedList.toArray(new Integer[0]),
						scanner.nextInt(),
						scanner.nextInt())) {
					System.out.println("交换失败，请重试");
					continue;
				}
				break;
			} catch (InputMismatchException inputMismatchException) {
				System.out.println("需输入两个数字");
			}
		}
	}
}

